package cn.accjiyun.qingcloud;

import cn.accjiyun.authority.Signature;
import cn.accjiyun.common.utils.JsonFormatTool;
import cn.accjiyun.common.utils.ParamUtil;
import org.apache.log4j.Logger;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.JacksonFeature;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.SimpleTimeZone;

/**
 * Created by jiyun on 2017/11/3.
 */
public class QingCloudRequestImpl implements QingCloudRequest {

    private static final Logger logger = Logger.getLogger(QingCloudRequestImpl.class);

    /**
     * 执行命令
     *
     * @param actionCode API指令
     * @param paramMap   参数对
     * @return 响应JSON字符串
     */
    @Override
    public String runAction(String actionCode, Map<String, String> paramMap) {
        paramMap.put("action", actionCode);
        if (!paramMap.containsKey("zone")) paramMap.put("zone", QingCloudConstants.ZONE);
        paramMap.put("time_stamp", formatDate(new SimpleDateFormat(QingCloudConstants.TIME_STAMP), new Date()));
        paramMap.put("access_key_id", QingCloudConstants.ACCESS_KEY_ID);
        paramMap.put("version", QingCloudConstants.VERSION);
        paramMap.put("signature_method", QingCloudConstants.SIGNATURE_METHOD);
        paramMap.put("signature_version", QingCloudConstants.SIGNATURE_VERSION);
        paramMap.put("signature", Signature.getSignature(paramMap, QingCloudConstants.SIGNATURE_METHOD));
        return sendRequest(QingCloudConstants.ENDPOINT + "?" + ParamUtil.paramsToURL(paramMap));
    }

    /**
     * 发送请求
     *
     * @param urlStr 请求URL
     * @return 响应JSON字符串
     */
    @Override
    public String sendRequest(String urlStr) {
        logger.info(urlStr);
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(JacksonFeature.class);
        Client client = ClientBuilder.newClient(clientConfig);
        WebTarget webTarget = client.target(urlStr);
        Response response = webTarget.request().get();
        String resultJson = response.readEntity(String.class);
        return JsonFormatTool.formatJson(resultJson);
    }

    /**
     * 格式化时间戳
     * @param dateFormat 时间格式
     * @param date 当前时间
     * @return 时间戳字符串
     */
    private String formatDate(SimpleDateFormat dateFormat, Date date) {
        dateFormat.setTimeZone(new SimpleTimeZone(8 * 60 * 60 * 1000, "GMT"));
        return dateFormat.format(date);
    }


}
